//
//  RankVC.swift
//  MM2
//
//  Created by 李成明 on 2022/1/7.
//

import UIKit
import CLImagePickerTool

class RankVC: MViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        rankList.request()
    }
        
    private lazy var bgImageView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "rank_bg_img")
        return view
    }()
    
    private lazy var rankList: RankListView = {
        let view = RankListView.init(frame: CGRect(x: 16, y: kStateAndNavH, width: kScreenWidth - 32, height: kScreenHeight - kStateAndNavH))
        view.fight { [weak self] model in
            self?.fightAction(model: model)
        }
        return view
    }()
    
    private lazy var navBar: MNavBar = {
        let view = MNavBar.init(frame: CGRect(x: 16, y: kStateBarHeight, width: kScreenWidth, height: kNaviBarHeight))
        view.back { [ weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
        view.title = "排行榜"
        return view
    }()
    
    private lazy var bottomView: RankBottomSliderView = {
        let view = RankBottomSliderView(frame: CGRect.zero)
        view.pkClick { [weak self] model in
            self?.pickPhoto(isPk: true, model: model)
        }.addClick { [weak self] in
            self?.pickPhoto(isPk: false)
        }.onLinePkClick { [weak self] in
            let vc = OnlinePkVC()
            self?.navigationController?.pushViewController(vc, animated: true)
        }
        return view
    }()
}

extension RankVC {
    private func setupUI() {
        view.addsubViews([bgImageView, navBar, rankList, bottomView])
        bgImageView.frame = view.bounds
    }
    
    private func fightAction(model: RankListModel) {
        bottomView.setPkModel(model: model).show()
    }
    
    private func pickPhoto(isPk: Bool, model: RankListModel? = nil) {
        
        let imgTool = CLImagePickerTool()
        imgTool.singleImageChooseType = .singlePicture
        imgTool.cl_setupImagePickerWith(MaxImagesCount: 1, superVC: self) { asset, image in
            CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 1) { img, _ in
                let vc: MViewController
                if isPk {
                    vc = RankPkVC()
                    (vc as? RankPkVC)?.pkUserModel = model
                    (vc as? RankPkVC)?.image = img
                } else {
                    vc = SingleAnalyzeVC()
                    (vc as? SingleAnalyzeVC)?.image = img
                }
                
                self.navigationController?.pushViewController(vc, animated: true)
                self.bottomView.hide()
            } failedClouse: {
                self.view.showToast(text: "既然看到了这个，那应该是出bug了")
            }
        }
    }
    
}
